package edu.itla.medifacil.controllers;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.itla.medifacil.helpers.Utilities;
import edu.itla.medifacil.persistence.entities.Appointment;
import edu.itla.medifacil.persistence.entities.People;
import edu.itla.medifacil.persistence.enums.Role;
import edu.itla.medifacil.persistence.managers.AppointmentManager;
import edu.itla.medifacil.persistence.managers.PersonManager;


/**
 * Servlet implementation class Appointments
 */

public class Appointments extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final AppointmentManager appointmentManager;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Appointments() {
        super();
        this.appointmentManager = new AppointmentManager();
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PersonManager personManager = new PersonManager();
		List<People> doctors  = personManager.findAll( Role.DOCTOR.getId() );
		List<People> patients  = personManager.findAll( Role.PATIENT.getId() );
		List<Appointment> appointments = appointmentManager.findAll();
		
		request.getSession(true).setAttribute("doctors", doctors);
		request.getSession().setAttribute("patients", patients);
		request.getSession().setAttribute("appointments", appointments);
		
		response.sendRedirect("appointments/");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if( request.getParameter("action").equals("save") ){
			Map<String, String> parameters = Utilities.parametersArrayToMap( request.getParameterMap() );
			appointmentManager.save(parameters);
			
			response.sendRedirect("Appointments.do");
		}
	}

}
